﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using 安检系统.Utils;
using 安检系统;

namespace 安检系统.Utils
{
    public class HttpServer
    {
        public static event MMSendMsg sendMsgEvent;

        private int port = 9000;
        private HttpListener httpListener;

        public HttpServer()
        {
            this.httpListener = new HttpListener();
        }
        public HttpServer(int port) : this()
        {
            this.port = port;
        }
        public void Run()
        {
            this.httpListener.Prefixes.Add(string.Format("http://+:{0}/", this.port));
            this.httpListener.Start();
            this.httpListener.BeginGetContext(new AsyncCallback(GetContext), this.httpListener);
            Console.WriteLine("Listen Port:" + port);

            JObject jsonObj = new JObject();
            jsonObj.Add("type", "ServerStarted");

            SendMsg(jsonObj);
        }
        public bool IsListening()
        {
            return httpListener.IsListening;
        }
        private void GetContext(IAsyncResult ar)
        {
            HttpListener httpListener = ar.AsyncState as HttpListener;
            HttpListenerContext context = httpListener.EndGetContext(ar);  //接收到的请求context（一个环境封装体）

            httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener);  //开始 第二次 异步接收request请求

            HttpListenerRequest request = context.Request;  //接收的request数据
            HttpListenerResponse response = context.Response;  //用来向客户端发送回复

            string rawData;
            using (StreamReader reader = new StreamReader(request.InputStream))
            {
                rawData = reader.ReadToEnd();
            }
            
            string type = request.QueryString["type"];
            if (!string.IsNullOrEmpty(type))
            {
                try
                {
                    JObject jsonObj = JObject.Parse(rawData);

                    String cameraIP = (String)jsonObj["AlarmInfoPlate"]["ipaddr"];
                    String carno = (String)jsonObj["AlarmInfoPlate"]["result"]["PlateResult"]["license"];

                    Console.WriteLine("车牌号:" + carno);

                    JObject resultObj = new JObject();
                    resultObj.Add("type", "GetCarNo");
                    JObject resultDetailObj = new JObject();
                    resultDetailObj.Add("carNo", carno);
                    resultDetailObj.Add("inOut", type);
                    resultObj.Add("detail", resultDetailObj);

                    SendMsg(resultObj);

                    //服务器验证是否通行
                    try
                    {

                        String ip = App.GetBaseInfo().HttpServerIp;
                        String port = App.GetBaseInfo().HttpServerPort;

                        //String bodyJsonStr = "{\"gateCode\":\"" + gateCode + "\", \"carNo\":\"" + carno + "\", \"type\":\"" + type + "\"}";

                        //String result = HttpPostHelper.doHttpPost("http://" + ip + ":" + port + "/ytBill/carApproach", bodyJsonStr);
                        //JObject resJSON = JObject.Parse(result);
                        //string status = (string)resJSON.GetValue("status");
                        //string message = (string)resJSON.GetValue("msg");

                        //if ("success".Equals(status))
                        //{
                            //JObject checkResultObj = new JObject();
                            //checkResultObj.Add("type", "Check");
                            //checkResultObj.Add("inOut", type);
                            //checkResultObj.Add("result", true);
                            //checkResultObj.Add("message", "");
                            //SendMsg(checkResultObj);

                            //String comm = App.GetBaseInfo().IO_Com_PortName;
                            ////抬杆
                            //if ("in".Equals(type))
                            //{
                            //    String inOpenPort = App.GetBaseInfo().IO_In_Open_Port;
                            //    PortControlHelper.openDoor(comm, int.Parse(inOpenPort));
                            //}
                            //else if ("out".Equals(type))
                            //{
                            //    String outOpenPort = App.GetBaseInfo().IO_Out_Open_Port;
                            //    PortControlHelper.openDoor(comm, int.Parse(outOpenPort));
                            //}
                        //}
                        //else
                        //{
                        //    JObject checkResultObj = new JObject();
                        //    checkResultObj.Add("type", "Check");
                        //    checkResultObj.Add("inOut", type);
                        //    checkResultObj.Add("result", false);
                        //    checkResultObj.Add("message", message);
                        //    SendMsg(checkResultObj);
                        //}
                    }
                    catch (Exception ex)
                    {
                        JObject checkResultObj = new JObject();
                        checkResultObj.Add("type", "Check");
                        checkResultObj.Add("inOut", type);
                        checkResultObj.Add("result", false);
                        checkResultObj.Add("message", ex.ToString());
                        SendMsg(checkResultObj);
                    }
                }
                catch (Exception ex)
                    {
                        Console.WriteLine(ex.GetBaseException());
                }
            }

            using (Stream output = response.OutputStream)  //发送回复
            {
                byte[] buffer = Encoding.UTF8.GetBytes("ok");
                output.Write(buffer, 0, buffer.Length);
            }
        }

        public void SendMsg(JObject obj)
        {
            if(sendMsgEvent != null)
            {
                sendMsgEvent(obj);
            }
        }
    }
}
